﻿
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using Pub;
using System.Reflection;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

namespace LZQXT.Test
{
    public partial class FMain : Form
    {

        public List<Form> flst = new List<Form>();
        public Form ftmp = new Form();

        string optFile = Application.StartupPath + "\\opt.dat";
        COpt opt1 = new COpt();

        const int CLOSE_SIZE = 15;                                              //tabPage标签图片
        Bitmap image;      //绘制“Ｘ”号即关闭按钮

        public FMain()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 装载插件
        /// </summary>
        public void addPlug()
        {
            CDebug.EnterMethod("装载插件");

            FileInfo[] finf = (new DirectoryInfo(Application.StartupPath + "\\plug")).GetFiles("JT_*.dll");
            //CDebug.Send("" + finf.Length);

            for (int i = 0; i < finf.Length;i++ )
            {
                string fileName = finf[i].FullName;
                Assembly SampleAssembly;
                SampleAssembly = Assembly.LoadFrom(fileName);

                Type[] types = SampleAssembly.GetTypes();

                Type type;
                MethodInfo method;

                for (int j = 0; j < types.Length; j++)
                {
                    //CDebug.Send("" + j + "." + types[j].Name);
                    if (types[j].Name != "JTBOX") continue;

                    MemberInfo[] member1 = types[j].GetMembers();
                    for (int k = 0; k < member1.Length; k++)
                    {
                        if (member1[k].Name == "RegPlug")
                        {
                            try
                            {
                                type = types[j];
                                method = (MethodInfo)member1[k];
                                //CDebug.Send("" + k + "." + member1[k].Name);

                                Object[] newArgs = new Object[2];
                                newArgs[0] = flst;
                                newArgs[1] = imageList1;

                                Object instance = null;

                                if (!method.IsStatic)
                                {
                                    instance = Activator.CreateInstance(type);
                                }

                                Object obj = method.Invoke(instance, newArgs);
                                if (!Convert.ToBoolean(obj))
                                    CDebug.Send("加载插件失败：" + fileName);

                                break;
                            }
                            catch (Exception ex)
                            {
                                CDebug.SendError("发生错误：" + fileName);
                                CDebug.SendError(ex.ToString());
                            }
                            
                        }

                    }
                }


            }

            CDebug.ExitMethod("装载插件");
        }

        public void addNode()
        {
            treeView1.Nodes.Clear();
            menu_tools.DropDownItems.Clear();
            int i = 0;
            foreach (Form f1 in flst)
            {
                imageList1.Images[i] = Image.FromHbitmap(f1.Icon.ToBitmap().GetHbitmap()); 

                TreeNode tnode = new TreeNode();
                tnode.Text = f1.Text;
                tnode.ImageIndex = i;
                tnode.SelectedImageIndex = i;
                treeView1.Nodes.Add(tnode);

                ToolStripMenuItem menu1 = new ToolStripMenuItem();
                menu1.Text = f1.Text;
                menu1.Image = imageList1.Images[i];
                menu1.Click += new EventHandler(menu_tools_Click); 
                menu_tools.DropDownItems.Add(menu1);

                i++;
            }
        }

        //设置窗体父容器
        public void SetParentI(Form f1, Control c1)
        {
            //ftmp.Hide();
            f1.TopLevel = false;
            f1.FormBorderStyle = FormBorderStyle.None;
            //f1.Parent = c1;
            f1.Dock = DockStyle.Fill;
            f1.Show();
            //ftmp = f1;
            bool b_find = false;
            for(int i=0;i<tabControl1.TabPages.Count;i++)
            {
                if (tabControl1.TabPages[i].Text == f1.Text)
                {
                    b_find = true;
                    tabControl1.SelectedIndex = i;
                    break;
                }
            }

            if(!b_find)
            {
                TabPage tabPage = new TabPage();
                tabPage.Text = f1.Text;
                tabControl1.TabPages.Add(tabPage);
                tabControl1.SelectedIndex = tabControl1.TabPages.Count - 1;
                f1.Parent = tabControl1.TabPages[tabControl1.TabPages.Count - 1];
            }
        }

        private void FMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (!CPub.MsgBox("确定要退出吗？", "退出"))
            {
                e.Cancel = true;
            }

            //保存列表
            if (opt1 == null) opt1 = new COpt();
            if (opt1.flst == null) opt1.flst = new List<string>();

            opt1.flst.Clear();
            for (int i = 0; i < flst.Count;i++ )
            {
                opt1.flst.Add(flst[i].Text);
            }

            Serialize(opt1, optFile);
        }

        private void plugOrder()
        {
            if (opt1 == null || opt1.flst == null) return;
            if (flst == null) return;
            try
            {
                //排序
                for (int i = 0; i < opt1.flst.Count; i++)
                {
                    if (opt1.flst[i] != flst[i].Text)
                    {
                        for (int j = i; j < flst.Count; j++)
                        {
                            //交换后退出循环
                            if (opt1.flst[i] == flst[j].Text)
                            {

                                Form f1 = flst[i];
                                flst[i] = flst[j];
                                flst[j] = f1;

                                Image img1 = imageList1.Images[i];
                                imageList1.Images[i] = imageList1.Images[j];
                                imageList1.Images[j] = img1;

                                break;
                            }
                        }
                    }
                }
            }
            catch (System.Exception ex)
            {
                CDebug.SendError(ex.ToString());
            }
            
        }

        private void FMain_Load(object sender, EventArgs e)
        {
            panel1.Dock = DockStyle.Fill;
            tabControl1.Dock = DockStyle.Fill;
            tabControl1.TabPages.Clear();

            treeView1.Visible = !treeView1.Visible;
            splitter1.Visible = treeView1.Visible;
            toolStrip1.Visible = false;

            image = new Bitmap(Application.StartupPath + "\\exit.png");
            this.tabControl1.DrawMode = TabDrawMode.OwnerDrawFixed;
            this.tabControl1.Padding = new System.Drawing.Point(CLOSE_SIZE, CLOSE_SIZE);

            //读取列表
            //opt1 = Deserialize(optFile);

            //addPlug();

            //plugOrder();

            addNode();
        }

        private void btn_Click(object sender, EventArgs e)
        {
            int i_btn = 0;
            ToolStripMenuItem menu_btn = null;
            if (sender is ToolStripButton) i_btn = Convert.ToInt32(((ToolStripButton)sender).Tag);
            if (sender is ToolStripMenuItem)
            {
                menu_btn = (ToolStripMenuItem)sender;
                i_btn = Convert.ToInt32(menu_btn.Tag);
            }

            switch (i_btn)
            {
                case 1:     //show or hide plug list
                    treeView1.Visible = !treeView1.Visible;
                    splitter1.Visible = treeView1.Visible;
                    break;
                case 2:     //exit
                    Close();
                    break;
                case 3:     // dbconfig
                    //Program.fdbinit.ShowDialog();
                    break;
                case 4:     //view toolbar
                    menu_btn.Checked = !menu_btn.Checked;
                    toolStrip1.Visible = menu_btn.Checked;
                    break;
                case 5:     //view plug list
                    menu_btn.Checked = !menu_btn.Checked;
                    treeView1.Visible = menu_btn.Checked;
                    splitter1.Visible = treeView1.Visible;
                    break;
            }
        }

        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            foreach (Form f1 in flst)
            {
                if (f1.Text == treeView1.SelectedNode.Text)
                {
                    SetParentI(f1, panel1);
                }
            }
        }


        /// <summary>
        /// 序列化
        /// </summary>
        /// <param name="obj1"></param>
        /// <param name="fileName"></param>
        public static void Serialize(COpt obj1, string fileName)
        {
            try
            {
                //创建二进制文件temp.dat
                FileStream fileStream = new FileStream(fileName, FileMode.Create);
                BinaryFormatter b = new BinaryFormatter();

                //将Student实例对象序列化给fileStream流：其含义是这时候的Student对象已经存储到temp.dat 文件中
                b.Serialize(fileStream, obj1);
                fileStream.Flush();
                fileStream.Close();
                fileStream.Dispose();
            }
            catch (System.Exception ex)
            {
                CDebug.SendError(ex.ToString());
            }
        }

        /// <summary>
        /// 反序列化
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static COpt Deserialize(string fileName)
        {
            COpt obj1 = new COpt();
            try
            {
                FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                //BinaryFormatter b = new BinaryFormatter();
                //将temp.dat 的文件流反序列化为Student
                //obj1 = b.Deserialize(fileStream);

                IFormatter formatter = new BinaryFormatter();
                formatter.Binder = new UBinder();
                obj1 = (COpt)formatter.Deserialize(fileStream);
                //释放文件流资源
                fileStream.Flush();
                fileStream.Close();
                fileStream.Dispose();
            }
            catch (System.Exception ex)
            {
                CDebug.SendError(ex.ToString());
            }
            return obj1;
        }

        private void btnUp_Click(object sender, EventArgs e)
        {
            if (treeView1.SelectedNode == null) return;
            int i = treeView1.SelectedNode.Index;
            if(i<1) return;

            Form f1 = flst[i - 1];
            flst[i - 1] = flst[i];
            flst[i] = f1;

            Image img1 = imageList1.Images[i - 1];
            imageList1.Images[i - 1] = imageList1.Images[i];
            imageList1.Images[i] = img1;

            addNode();
        }

        private void btnDown_Click(object sender, EventArgs e)
        {
            if (treeView1.SelectedNode == null) return;
            int i = treeView1.SelectedNode.Index;
            if (i >= flst.Count - 1) return;

            Form f1 = flst[i + 1];
            flst[i + 1] = flst[i];
            flst[i] = f1;

            Image img1 = imageList1.Images[i + 1];
            imageList1.Images[i + 1] = imageList1.Images[i];
            imageList1.Images[i] = img1;

            addNode();
        }

        private void menu_tools_Click(object sender, EventArgs e)
        {
            string sTxt = (sender as ToolStripMenuItem).Text;
            foreach (Form f1 in flst)
            {
                if (f1.Text == sTxt)
                {
                    SetParentI(f1, panel1);
                }
            }
        }

        private void tabControl1_DrawItem(object sender, DrawItemEventArgs e)
        {
            try
            {
                Rectangle myTabRect = this.tabControl1.GetTabRect(e.Index);

                //先添加TabPage属性   
                e.Graphics.DrawString(this.tabControl1.TabPages[e.Index].Text,
                    this.Font, SystemBrushes.ControlText, myTabRect.X + 2, myTabRect.Y + 2);

                //再画一个矩形框
                using (Pen p = new Pen(Color.White))
                {
                    myTabRect.Offset(myTabRect.Width - (CLOSE_SIZE + 3), 2);
                    myTabRect.Width = CLOSE_SIZE;
                    myTabRect.Height = CLOSE_SIZE;
                    e.Graphics.DrawRectangle(p, myTabRect);
                }

                //填充矩形框
                Color recColor = e.State == DrawItemState.Selected ? Color.White : Color.White;
                using (Brush b = new SolidBrush(recColor))
                {
                    e.Graphics.FillRectangle(b, myTabRect);
                }

                //画关闭符号
                using (Pen objpen = new Pen(Color.Black))
                {
                    /*
                    //"\"线
                    Point p1 = new Point(myTabRect.X + 3, myTabRect.Y + 3);
                    Point p2 = new Point(myTabRect.X + myTabRect.Width - 3, myTabRect.Y + myTabRect.Height - 3);
                    e.Graphics.DrawLine(objpen, p1, p2);

                    //"/"线
                    Point p3 = new Point(myTabRect.X + 3, myTabRect.Y + myTabRect.Height - 3);
                    Point p4 = new Point(myTabRect.X + myTabRect.Width - 3, myTabRect.Y + 3);
                    e.Graphics.DrawLine(objpen, p3, p4);
                    */

                    ////=============================================
                    Bitmap bt = new Bitmap(image);
                    Point p5 = new Point(myTabRect.X, 4);
                    e.Graphics.DrawImage(bt, p5);
                    //e.Graphics.DrawString(this.tabCtrl_Txt.TabPages[e.Index].Text, this.Font, objpen.Brush, p5);

                }


                //绘制小图标              
                //==============================================================================
                //Bitmap bt = new Bitmap("E:\\1\\2.jpg");
                //Point p5 = new Point(4, 4);
                ////e.Graphics.DrawImage(bt, e.Bounds);
                //e.Graphics.DrawImage(bt, p5);
                //Pen pt = new Pen(Color.Red);
                ////e.Graphics.DrawString(this.tabCtrl_Txt.TabPages[e.Index].Text, this.Font, pt.Brush, e.Bounds);
                //e.Graphics.DrawString(this.tabCtrl_Txt.TabPages[e.Index].Text, this.Font, pt.Brush, p5);

                e.Graphics.Dispose();
            }
            catch (Exception ex)
            {
                CDebug.SendError(ex.ToString());
            }
        }

        private void tabControl1_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                int x = e.X, y = e.Y;

                //计算关闭区域   
                Rectangle myTabRect = this.tabControl1.GetTabRect(this.tabControl1.SelectedIndex);

                myTabRect.Offset(myTabRect.Width - (CLOSE_SIZE + 3), 2);
                myTabRect.Width = CLOSE_SIZE;
                myTabRect.Height = CLOSE_SIZE;

                //如果鼠标在区域内就关闭选项卡   
                bool isClose = x > myTabRect.X && x < myTabRect.Right
                 && y > myTabRect.Y && y < myTabRect.Bottom;

                if (isClose == true)
                {
                    //lstDoc.RemoveAt(this.tabControl1.SelectedIndex);
                    this.tabControl1.TabPages.Remove(this.tabControl1.SelectedTab);
                }
            }
        }
    }
    [Serializable]
    public class COpt
    {
        public List<string> flst;
    }
}